import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Checkbox, Select } from 'zent';
import { Select as SelectAnt, Popconfirm } from 'antd';
import SKUContainer from './SKUContainer';
import { connect } from 'dva';
import { parse } from 'url';

const noop = res => res;
const Option = SelectAnt.Option;
class SKUGroup extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      newSKUText: '',
      hasSKUImage: props.sku.leaf
        ? props.sku.leaf.some(item => item.img_url)
        : false,
    };
  }

  filterHandler = (item, keyword) => {
    let { maxSKUTextLength } = this.context;
    if (maxSKUTextLength && maxSKUTextLength > 0) {
      keyword = keyword.substring(0, maxSKUTextLength);
    }
    return item.text.indexOf(keyword) > -1;
  };

  // 选择sku
  selectSKUHandler = (evt, sku) => {

    let { index, onSKUChange } = this.props;
    let { optionValue, optionText } = this.context;
    sku.leaf = [];
    if (sku[optionValue] === this.props.sku[optionValue]) return;
    if (sku[optionValue]) {
      onSKUChange(sku, index);
      return;
    }
    this.createSKU(sku[optionText], index);
  };
  // 选择sku
  selectSKUHandlerByAnt = (evt, value) => {
    this.handleReset()
    if (value.key == 0) {
      //如果长度大于5 直接截取 5长度
      let porpsName = value.props.children
      if (porpsName.length > 5) {
        porpsName = porpsName.substring(0, 5)
      }
      return this.createSkuProp(porpsName);
    }
    let sku = { id: parseInt(value.key), leaf: [], text: value.props.children, value: parseInt(value.key) }
    let { index, onSKUChange } = this.props;
    let { optionValue, optionText } = this.context;

    if (sku[optionValue] === this.props.sku[optionValue]) return;
    if (sku[optionValue]) {
      onSKUChange(sku, index);
      return;
    }
    this.createSKU(sku[optionText], index);
    // 选中之后 清空条件  这样失去焦点时 不会添加

  };

  createSkuProp = (value) => {
    let { dispatch, skuTree } = this.props;
    let sname = value;
    if (!sname) {
      return;
    }
    let rparam = { name: sname };
    if (skuTree.filter(i => i.id == 0).length > 0) {
      let index = skuTree.findIndex(item => item.id == 0);
      skuTree.splice(index, 1);
    }
    let index = skuTree.filter(item => item.text == sname).length;
    if (index > 0) {
      return;
    }
    dispatch({
      type: 'goods/CreateProductSku',
      params: rparam,
      callBack: (data) => {
        if (data.Code == 0) {
          let sku = { id: data.Data.id, leaf: [], text: sname, value: data.Data.id }
          let { index, onSKUChange, skuTree } = this.props;
          let { optionValue, optionText } = this.context;
          if (sku[optionValue] === this.props.sku[optionValue]) return;
          if (sku[optionValue]) {
            onSKUChange(sku, index);
            return;
          }
          this.createSKU(sku[optionText], index);
          this.setState({ newSKUText: '' })

        }
      }
    })
  }

  // 创建sku
  createSKU(text) {
    let { sku, index, onSKUChange } = this.props;
    let { onCreateGroup, optionValue, optionText } = this.context;
    onCreateGroup(text).then(data => {
      if (data > 0) {
        sku[optionValue] = data;
        sku[optionText] = text;
        this.setState({
          newSKUText: '',
        });
        onSKUChange(sku, index);
      }
    });
  }

  asyncFilterSKU = keyword => {
    let { skuTree, index } = this.props;
    let { optionText, maxSKUTextLength } = this.context;
    if (maxSKUTextLength && maxSKUTextLength > 0) {
      keyword = keyword.substring(0, maxSKUTextLength);
    }
    if (skuTree.some(item => item[optionText] === keyword)) return;

    this.setState({
      newSKUText: keyword,
    });
  };

  onSKULeafChange = leaf => {

    let { sku, index, onSKUChange } = this.props;
    sku.leaf = leaf;
    onSKUChange(sku, index);
  };

  rebuildSKULeaf(sku, index) {
    let { subGroup } = this.state;
    if (subGroup[index]) {
      subGroup[index].leaf = [].concat(sku);
    }
    this.setState({ subGroup });
    this.props.onChange(subGroup);
  }

  checkSKUImage = evt => {
    let { sku, index, onSKUChange } = this.props;
    let isShow = evt.target.checked;
    sku.is_show = isShow;
    sku.leaf = sku.leaf.map(item => {
      item.is_show = isShow;
      return item;
    });
    this.setState({
      hasSKUImage: isShow,
    });
    onSKUChange(sku, index);
  };

  handleReset = () => {
    this.setState({
      newSKUText: '',
    });
  };
  handleSearch = (value) => {
    let { skuTree, onSKUChange, index } = this.props;
    //fetch(value, data => this.setState({ data }));
    let sku = { id: 0, leaf: [], text: value, value: 0 }
    if (skuTree.filter(i => i.id == 0).length > 0) {
      let index = skuTree.findIndex(item => item.id == 0);
      skuTree.splice(index, 1);
    }
    // this.setState({
    //   newSKUText: value,
    // });

    if (skuTree.filter(i => i.text == value).length < 1) {
      skuTree.push(sku);
      onSKUChange(sku, index);
    }
  }
  render() {
    let { sku, index, skuTree, i18n } = this.props;
    let { optionValue, optionText } = this.context;
    let { newSKUText, hasSKUImage } = this.state;
    const prefix = `${this.context.prefix}-group`;

    // if (newSKUText) {
    //   skuTree = [].concat(skuTree);
    //   if (skuTree[0][optionValue] === 0) {
    //     skuTree[0][optionText] = newSKUText;
    //   } else {
    //     let newSKU = {};
    //     newSKU[optionValue] = 0;
    //     newSKU[optionText] = newSKUText;
    //     skuTree.unshift(newSKU);
    //   }
    // }

    return (
      <div className={prefix}>
        <h3 className="group-title">
          {/* <Select
            open={typeof sku[optionValue] === 'undefined'}
            optionValue={optionValue}
            data={skuTree}
            onChange={this.selectSKUHandler}
            filter={this.filterHandler}
            onAsyncFilter={this.asyncFilterSKU}
            onOpen={this.handleReset}
            value={sku[optionValue] || ''}
          /> */}
          规格名：
          <SelectAnt
            onChange={this.selectSKUHandlerByAnt}
            //onBlur={this.createSkuProp}
            //placeholder={"最多五个字符"}
            onSearch={this.handleSearch}
            style={{ width: 200, marginRight: 8, }}
            showArrow={false}
            showSearch
            value={sku[optionValue] ? sku[optionValue] + '' : ''}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {
              skuTree && skuTree.map(item =>

                item.id || item.id === 0 ? <Option key={item.id}>{item.text}</Option > : null
              )
            }
          </SelectAnt>
          {index === 0 ? (
            <Checkbox checked={hasSKUImage} onChange={this.checkSKUImage} style={{ verticalAlign: 'text-bottom' }}>
              {i18n.group.add}
            </Checkbox>
          ) : (
              ''
            )}
          <Popconfirm title="确认删除？" onConfirm={this.props.onSKUDelete} okText="是" cancelText="否">
            <span className="group-remove" style={{ backgroundColor: 'rgba(0, 0, 0, .2)' }}>
              ×
          </span>
          </Popconfirm>
        </h3>
        <SKUContainer
          sku={{ ...sku }}
          i18n={i18n}
          hasSKUImage={hasSKUImage}
          onSKULeafChange={this.onSKULeafChange}
        />
        {hasSKUImage ? (
          <div className="sku-group-cont">
            <p className="help-block">{i18n.group.imageTip1}</p>
            <p className="help-block">{i18n.group.imageTip2}</p>
            <p className="help-block">{i18n.group.imageTip3}</p>
          </div>
        ) : (
            <div className="sku-group-cont" ></div>
          )}
      </div>
    );
  }
}

SKUGroup.contextTypes = {
  prefix: PropTypes.string,
  maxSKUTextLength: PropTypes.number,
  optionValue: PropTypes.string,
  optionText: PropTypes.string,
  onCreateGroup: PropTypes.func,
};

SKUGroup.propTypes = {
  index: PropTypes.number,
  sku: PropTypes.object.isRequired,
  onSKUDelete: PropTypes.func,
  onSKUChange: PropTypes.func,
};

SKUGroup.defaultProps = {
  index: 0,
  data: {},
  onSKUDelete: noop,
  onSKUChange: noop,
};

export default connect(({ goods, global, loading }) => ({
  goods,
}))(SKUGroup);


